"""
基础设备Python绑定
提供所有设备通用的基础接口
"""

import ctypes
from typing import List, Optional, Tuple
from enum import IntEnum


class LockzhinerADCVoltage(IntEnum):
    """ADC电压量程枚举"""
    ADCVoltage_None = -1      # 未知电压量程
    ADCVoltage_0_1_V = 0      # 0.1V电压量程
    ADCVoltage_0_2_V = 1      # 0.2V电压量程
    ADCVoltage_0_5_V = 2      # 0.5V电压量程
    ADCVoltage_1_V = 3        # 1V电压量程
    ADCVoltage_2_V = 4        # 2V电压量程
    ADCVoltage_2_5_V = 5      # 2.5V电压量程
    ADCVoltage_5_V = 6        # 5V电压量程
    ADCVoltage_10_V = 7       # 10V电压量程
    ADCVoltage_15_V = 8       # 15V电压量程
    ADCVoltage_20_V = 9       # 20V电压量程
    ADCVoltage_50_V = 10      # 50V电压量程
    ADCVoltage_60_V = 11      # 60V电压量程
    ADCVoltage_100_V = 12     # 100V电压量程


class DAQADCTriggerSource(IntEnum):
    """ADC触发源配置枚举"""
    TriggerSourceSoftware = 0  # 软件触发源


class LockzhinerADCSampleRate(IntEnum):
    """ADC采样率枚举"""
    ADCSampleRate_None = 0          # 未知采样率
    ADCSampleRate_1 = 1             # 1采样率
    ADCSampleRate_10 = 10           # 10采样率
    ADCSampleRate_100 = 100         # 100采样率
    ADCSampleRate_200 = 200         # 200采样率
    ADCSampleRate_500 = 500         # 500采样率
    ADCSampleRate_1_K = 1000        # 1K采样率
    ADCSampleRate_2_K = 2000        # 2K采样率
    ADCSampleRate_5_K = 5000        # 5K采样率
    ADCSampleRate_10_K = 10000      # 10K采样率
    ADCSampleRate_20_K = 20000      # 20K采样率
    ADCSampleRate_50_K = 50000      # 50K采样率
    ADCSampleRate_100_K = 100000    # 100K采样率
    ADCSampleRate_200_K = 200000    # 200K采样率
    ADCSampleRate_500_K = 500000    # 500K采样率
    ADCSampleRate_800_K = 800000    # 800K采样率
    ADCSampleRate_1_M = 1000000     # 1M采样率
    ADCSampleRate_2_M = 2000000     # 2M采样率
    ADCSampleRate_5_M = 5000000     # 5M采样率
    ADCSampleRate_10_M = 10000000   # 10M采样率
    ADCSampleRate_20_M = 20000000   # 20M采样率
    ADCSampleRate_50_M = 50000000   # 50M采样率
    ADCSampleRate_65_M = 65000000   # 65M采样率
    ADCSampleRate_100_M = 100000000 # 100M采样率
    ADCSampleRate_125_M = 125000000 # 125M采样率
    ADCSampleRate_250_M = 250000000 # 250M采样率


class LockzhinerADCChannel(IntEnum):
    """ADC通道枚举"""
    ADCChannelAINNone = 0b00000000  # 全不选 | 软件触发
    ADCChannelAIN1 = 0b00000001     # ADC通道1
    ADCChannelAIN2 = 0b00000010     # ADC通道2
    ADCChannelAIN3 = 0b00000100     # ADC通道3
    ADCChannelAIN4 = 0b00001000     # ADC通道4
    ADCChannelAIN5 = 0b00010000     # ADC通道5
    ADCChannelAIN6 = 0b00100000     # ADC通道6
    ADCChannelAIN7 = 0b01000000     # ADC通道7
    ADCChannelAIN8 = 0b10000000     # ADC通道8


class LockzhinerADCTriggerType(IntEnum):
    """ADC触发类型枚举"""
    Normal = 0x00           # 正常模式或滚动模式（不进行触发）
    RisingEdge = 0x01       # 上升沿
    FallingEdge = 0x02      # 下降沿
    DoubleEdge = 0x03       # 双边缘
    ExternalTrigger = 0x04  # 外部触发
    Error = 0x05


class LockzhinerADCTriggerMode(IntEnum):
    """ADC触发模式枚举"""
    Automatic = 0x00  # 自动触发
    Common = 0x01     # 普通触发
    Single = 0x02     # 单次触发
    Error = 0x04


class UpgradeFirmwareStatus(IntEnum):
    """固件升级状态枚举"""
    Idle = 0            # 空闲状态
    Start = 1           # 开始升级
    Erasing = 2         # 正在擦除
    Downloading = 3     # 正在下载
    ReadyNextData = 4   # 准备好接收下一次数据


class BaseDeviceBinding:
    """基础设备Python绑定类"""
    
    def __init__(self, dll_path: str):
        """
        初始化基础设备绑定
        
        Args:
            dll_path: DLL文件路径
        """
        self.dll = ctypes.CDLL(dll_path)
        self._device_handle = None
    
    def __del__(self):
        """析构函数，确保资源清理"""
        if self._device_handle:
            self.delete_device(self._device_handle)
    
    def create_device(self) -> Optional[ctypes.POINTER(ctypes.c_uint32)]:
        """
        创建设备实例（需要在子类中实现）
        
        Returns:
            设备句柄，失败返回None
        """
        raise NotImplementedError("子类必须实现此方法")
    
    def delete_device(self, handle: ctypes.POINTER(ctypes.c_uint32)) -> None:
        """
        删除设备实例（需要在子类中实现）
        
        Args:
            handle: 设备句柄
        """
        raise NotImplementedError("子类必须实现此方法")
    
    def use_backend(self, device_handle: ctypes.POINTER(ctypes.c_uint32), 
                    backend_handle: ctypes.POINTER(ctypes.c_uint32)) -> bool:
        """
        设置设备使用的后端（需要在子类中实现）
        
        Args:
            device_handle: 设备句柄
            backend_handle: 后端句柄
            
        Returns:
            是否成功
        """
        raise NotImplementedError("子类必须实现此方法")
    
    def initialize_device(self, handle: ctypes.POINTER(ctypes.c_uint32)) -> bool:
        """
        初始化设备（需要在子类中实现）
        
        Args:
            handle: 设备句柄
            
        Returns:
            是否成功
        """
        raise NotImplementedError("子类必须实现此方法")
    
    def connect_device(self, handle: ctypes.POINTER(ctypes.c_uint32)) -> bool:
        """
        连接设备（需要在子类中实现）
        
        Args:
            handle: 设备句柄
            
        Returns:
            是否成功
        """
        raise NotImplementedError("子类必须实现此方法")
    
    def disconnect_device(self, handle: ctypes.POINTER(ctypes.c_uint32)) -> bool:
        """
        断开设备连接（需要在子类中实现）
        
        Args:
            handle: 设备句柄
            
        Returns:
            是否成功
        """
        raise NotImplementedError("子类必须实现此方法")
    
    # 通用的辅助方法
    def _create_string_buffer(self, size: int = 256) -> ctypes.Array:
        """
        创建字符串缓冲区
        
        Args:
            size: 缓冲区大小
            
        Returns:
            字符串缓冲区
        """
        return ctypes.create_string_buffer(size)
    
    def _decode_string_buffer(self, buffer: ctypes.Array) -> str:
        """
        解码字符串缓冲区
        
        Args:
            buffer: 字符串缓冲区
            
        Returns:
            解码后的字符串
        """
        try:
            return buffer.value.decode('utf-8')
        except (UnicodeDecodeError, AttributeError):
            return ""
    
    def _create_int_array(self, data: List[int]) -> ctypes.Array:
        """
        创建整数数组
        
        Args:
            data: 整数列表
            
        Returns:
            C整数数组
        """
        return (ctypes.c_int * len(data))(*data)
    
    def _create_bool_array(self, data: List[bool]) -> ctypes.Array:
        """
        创建布尔数组
        
        Args:
            data: 布尔列表
            
        Returns:
            C布尔数组
        """
        return (ctypes.c_bool * len(data))(*data)
    
    def _create_float_array(self, size: int) -> ctypes.Array:
        """
        创建浮点数组
        
        Args:
            size: 数组大小
            
        Returns:
            C浮点数组
        """
        return (ctypes.c_float * size)()
    
    def _convert_float_array_to_list(self, array: ctypes.Array) -> List[float]:
        """
        将C浮点数组转换为Python列表
        
        Args:
            array: C浮点数组
            
        Returns:
            Python浮点数列表
        """
        return list(array) 